import axios from "axios";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
import { UserService } from '@/api/api'
const router = useRouter()

const request = axios.create({
    baseURL : import.meta.env.VITE_BASE_API,
    timeout : 50000,
    requestOptions :{
        withToken : true
    }
})

request.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token')
        if(token){
            config.headers.Authorization = 'Bearer ' + token
        }
        return config
    },
    (err) => {
        ElMessage.warning('请求超时')
        return Promise.reject(err)
    }
)
// 响应拦截
request.interceptors.response.use(
    (response) => {
        if(response.status == '200'){
            return Promise.resolve(response.data)
        }
    },
    (error) => {
        console.log('error', error);
        if(error.request.status){
            switch(error.request.status){
                case 401 :
                    if(localStorage.getItem('refresh_token')){
                        let params = {
                            refresh_token : localStorage.getItem('refresh_token'),
                            grant_type : "refresh_token",
                            scope : "server"
                        }
                        localStorage.removeItem('token')
                        UserService.login({...params}).then(res => {
                            localStorage.setItem('token', res.access_token)
                            localStorage.setItem('refresh_token', res.refresh_token)
                        })
                    }else{
                        ElMessage.error(error.message)
                        localStorage.removeItem('token');
                        router.push('/login')
                    }
                   
                case 404:
                    break;
                case 500:
                    break;
                default:
                    break;
            }
        }
        return Promise.reject(new Error(error.message))
    }
)
export default request;